<template>
  <div class="thirdparty-revenue report-container">
    <Row class="coinrevenue-list-edit">
      <Row type='flex'
           justify="space-between">
        <Row type='flex'
             align='middle'
             justify="space-between">
          <Row type='flex'
               align='middle'>
            <Col>
            <span>时间：</span>
            <datePickerYmd @on-change="search"
                           :dateOption="dateOption"
                           :dataType='dataType'
                           :selectDateType.sync='selectDateType'
                           v-model="timeDate"
                           style="display:inline-block"></datePickerYmd>
            </Col>
            <Row type='flex'
                 align='middle'
                 class="export-btn">
              <Col><span>支付方式：</span></Col>
              <Col>
              <Select v-model="payCode"
                      @on-change='changeSelect'
                      class="common-input">
                <Option v-for="item in selectPayCode"
                        :value="item.value"
                        :key="item.value">{{ item.label }}</Option>
              </Select>
              </Col>
            </Row>
            <Row type='flex'
                 align='middle'
                 class="export-btn">
              <Col><span>门店名称：</span></Col>
              <Col>
              <!-- <Select v-model="searchObj.shopId"
                      @on-change="selectshop"
                      multiple
                      class="select-shop-item"
                      filterable
                      :max-tag-count="1"
                      :max-tag-placeholder="maxTagPlaceholder"
                      style="width:210px">
                <Option v-for="item in shopList"
                        :value="item.shopId"
                        :key="item.shopId">{{ item.shopName }}</Option>
              </Select> -->
              <vueTreeselectChoice :multiple="true"
                                   ref="vueTreeselectChoice"
                                   @input="handleShop"
                                   @on-api-finish="apiFinish"
                                   permissionCode="moms:report:thirdpartyrevenue"
                                   v-model="ShopValue"></vueTreeselectChoice>
              <!-- <vueTreeselectShop :shopList.sync="searchObj.shopId"
                                 @id-change="search"
                                 :statusList.sync="statusList"
                                 permissionCode="moms:report:thirdpartyrevenue"
                                 v-model="testValue"></vueTreeselectShop> -->
              </Col>
              <Col>
              <Button type="primary"
                      class="coinrevenue-btn export-btn"
                      @click="search">查询</Button>
              </Col>
            </Row>
          </Row>
        </Row>
        <div id="third-filter">
          <Row type="flex">
            <Row type='flex'
                 align='middle'
                 justify="end">
              <Row type='flex'
                   align='middle'
                   justify="end">
                <Col>
                <Button v-if="hasPermission('moms:report:thirdpartyrevenueexport')" class="coinrevenue-btn concrete-data"
                        @click='exportData'>导出</Button>
                </Col>
              </Row>
              <Row type='flex'
                   align='middle'
                   justify="end">
                <Col>
                <Button v-if="exampleShow"
                        @click="exampleOpen"
                        class="coinrevenue-btn2 concrete-data">收起筛选
                  <Icon type="ios-arrow-down" />
                </Button>
                <Button v-else
                        @click="exampleOpen"
                        class="coinrevenue-btn2 concrete-data">更多筛选
                  <Icon type="ios-arrow-up" />
                </Button>
                </Col>
              </Row>
            </Row>
          </Row>
        </div>
      </Row>
      <div class="third-filter-show-ds">
        <Row type='flex'
             align='middle'
             class="marginTop"
             v-if="exampleShow">
          <Col><span>子商户：</span></Col>
          <Col>
          <Select v-model="payee"
                  @on-change="selectpayee"
                  class="common-input">
            <Option v-for="item in payeeList"
                    :value="item.paymentAccountId"
                    :key="item.paymentAccountId">{{ item.accountName }}</Option>
          </Select>
          </Col>
        </Row>
      </div>
      <div id="third-filter-show">
        <Row type="flex"
             justify="space-between"
             class="marginTop">
          <Row type='flex'
               align='middle'
               v-if="exampleShow">
            <Col><span>子商户：</span></Col>
            <Col>
            <Select v-model="payee"
                    @on-change="selectpayee"
                    class="common-input">
              <Option v-for="item in payeeList"
                      :value="item.paymentAccountId"
                      :key="item.paymentAccountId">{{ item.accountName }}</Option>
            </Select>
            </Col>
          </Row>
          <!-- <Row type="flex"
               justify="end"> -->
          <!-- <Col> -->
          <div id="exportData-filter">
            <Button class="coinrevenue-btn concrete-data"
                    @click='exportData'
                    v-if="hasPermission('moms:report:thirdpartyrevenueexport')">导出</Button>
            <!-- </Col> -->
            <!-- <Col> -->
            <Button v-if="exampleShow"
                    @click="exampleOpen"
                    class="coinrevenue-btn2 concrete-data">收起筛选
              <Icon type="ios-arrow-down" />
            </Button>
            <Button v-else
                    @click="exampleOpen"
                    class="coinrevenue-btn2 concrete-data">更多筛选
              <Icon type="ios-arrow-up" />
            </Button>
          </div>
          <!-- </Col> -->
          <!-- </Row> -->
        </Row>
      </div>
    </Row>
    <Table stripe
           border
           :height="this.tableHeight"
           :loading='loading'
           class="table-list"
           ref="rowSpanTable"
           :columns="columns"
           :data="resData">
      <template slot-scope="{ row }"
                slot="payCode">
        <span>{{{cmb:'招商聚合',alipay:'支付宝',weixin:'微信' }[row.payCode]}}</span>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:thirdpartyrevenue"
                 v-if="hasPermission('moms:report:thirdpartyrevenueexport')"></down-center>
  </div>
</template>
<script>
import '../../report.less'
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { thirdPayment, exportThird, paySubmerchant } from '@/api/report/finance'
import { formatAmount } from '@/libs/tools'
import { blobToXls } from '@/libs/blobToXls'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
import DownCenter from '@/view/components/down-center/index.vue'
import errorCaptured from '@/libs/errorCaptured'
export default {
  name: 'report_finance_thirdpartyrevenue',
  components: { vueTreeselectChoice, datePickerYmd, DownCenter },
  data () {
    return {
      exampleShow: true,
      dataChoose: 'range',
      testValue: [],
      total: 0,
      tableHeight: 0,
      ShopValue: [],
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'daterange', value: '自定义' }],
      timeDate: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00')],
      selectDateType: 'date',
      statusList: false,
      options: [],
      loading: false,
      value: null,
      shopName: null,
      resData: [],
      shopList: [],
      searchObj: {
        shopId: [],
        startDate: '',
        endDate: '',
        offset: 1,
        limit: 10
      },
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      payCode: '-1', // 支付方式
      selectPayCode: [
        { value: '-1', label: '全部' },
        { value: 'weixin', label: '微信' },
        { value: 'alipay', label: '支付宝' },
        { value: 'cmb', label: '招商聚合' }
      ], // 支付方式
      payee: '-1',
      startPayee: [],
      payeeList: [
      ],
      columns: [
        { title: '门店', key: 'shopName', align: 'center', width: 200 },
        { title: '日期', key: 'statDate', align: 'center', width: 200 },
        { title: '支付方式', key: 'payCode', align: 'center', width: 200, slot: 'payCode' },
        { title: '收款方', key: 'payee', align: 'center', width: 200 },
        { title: '子商户', key: 'subMerchantName', align: 'center', width: 200 },
        { title: '支付金额(元)', key: 'payAmount', align: 'center', width: 200 },
        { title: '退款金额(元)', key: 'refundAmount', align: 'center', width: 200 },
        { title: '手续费(元)', key: 'serviceAmount', align: 'center', width: 200 },
        { title: '结算金额(元)', key: 'settleAmount', align: 'center', width: 200 },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          render: (h, params) => {
            if (params.row.payCode !== 'cmb') return null
            return h('i', {
              class: ['iconsys', 'icondetail'],
              attrs: {
                title: '查看详情'
              },
              on: {
                click: () => {
                  // let obj = { 'daterange': '3', 'month': '1', 'date': '0' }
                  // console.log('详情', params)
                  this.$router.push({
                    name: 'report_finance_thirdpartyrevenue_detail',
                    params: { startDate: this.startDate, endDate: this.endDate, shopId: params.row.shopId, shopName: params.row.shopName, dateType: this.selectDateType, t: +new Date() },
                    query: { t: +new Date() }
                  })
                }
              }
            })
          }
        }
      ]
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      if (this.selectDateType === 'daterange') return dayjs(this.timeDate[1]).add(1, 'day').format('YYYY-MM-DD 00:00:00')
      return this.timeDate[1]
    }
  },
  mounted () {

  },
  updated () {
    this.$nextTick(() => {
      // rowSpanTable(this.$refs.rowSpanTable, 'shopName')
    })
  },
  methods: {
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      this.search()
    },
    apiFinish () {
      this.ShopValue = null
    },
    selectpayee (val) {
    },
    filtersResData (data) {
      data.map(ele => {
        Object.keys(ele).forEach(key => {
          if (key === 'payAmount' || key === 'refundAmount' || key === 'serviceAmount' || key === 'settleAmount') {
            ele[key] = formatAmount(ele[key])
          }
        })
      })
      return data
    },
    // 导出
    exportData () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        let obj = { 'daterange': '3', 'month': '1', 'date': '0' }
        this.$refs.downCenterRef.addTask({
          merchantId: this.$store.state.user.merchantId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate,
          dateType: obj[this.selectDateType],
          taskModule: 'thirdPayment',
          extraMapParam: {
            payCode: this.payCode === '-1' ? '' : this.payCode,
            subMerchantId: this.payee === '-1' ? '' : this.payee
          }
        })
        // this.exportTable(obj[this.selectDateType])
      }
    },
    // 选择收款方
    changeSelect (val) {
      // this.payeeList = []
      // this.startPayee = []
      // this.$set(this, 'payee', '')
      this.payee = '-1'
      paySubmerchant({
        merchantId: this.$store.state.user.merchantId,
        providerCode: val === '-1' ? '' : val
      }).then(res => {
        if (res.data.status === 200) {
          this.startPayee = res.data.data
          this.startPayee.unshift({
            accountName: '全部',
            paymentAccountId: '-1'
          })
          this.payeeList = this.startPayee
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    search () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        let obj = { 'daterange': '2', 'month': '1', 'date': '0' }
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getList(obj[this.selectDateType])
      }
    },
    async getList (type) {
      this.loading = true
      this.resData = []
      this.tableHeight = 0
      const [err, res] = await errorCaptured(thirdPayment, {
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        // shopIds: ['01cbe551-cf9d-4b67-95a4-7b897563388c'],
        // shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit,
        payCode: this.payCode === '-1' ? '' : this.payCode,
        dateType: type,
        subMerchantId: this.payee === '-1' ? '' : this.payee
      })
      this.loading = false
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(res.data.error)
      this.total = res.data.totalCount
      if (res.data.data && res.data.data.length >= 14) {
        this.tableHeight = 520
      }
      this.resData = res.data.data ? this.filtersResData(res.data.data) : []
      // thirdPayment({
      //   merchantId: this.$store.state.user.merchantId,
      //   shopIds: this.searchObj.shopId,
      //   // shopIds: ['01cbe551-cf9d-4b67-95a4-7b897563388c'],
      //   // shopIds: this.searchObj.shopId,
      //   startDate: this.startDate,
      //   endDate: this.endDate,
      //   offset: (this.searchObj.offset - 1) * this.searchObj.limit,
      //   limit: this.searchObj.limit,
      //   payCode: this.payCode === '-1' ? '' : this.payCode,
      //   dateType: type,
      //   subMerchantId: this.payee === '-1' ? '' : this.payee
      // }).then(res => {
      //   this.loading = false
      //   if (res.data.status === 200) {
      //     this.total = res.data.totalCount
      //     if (res.data.data && res.data.data.length >= 14) {
      //       this.tableHeight = 520
      //     }
      //     this.resData = res.data.data ? this.filtersResData(res.data.data) : []
      //   } else {
      //     this.$Message.error(`${res.data.error}`)
      //   }
      // })
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      let obj = { 'daterange': '2', 'month': '1', 'date': '0' }
      this.getList(obj[this.selectDateType])
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      let obj = { 'daterange': '2', 'month': '1', 'date': '0' }
      this.getList(obj[this.selectDateType])
    },
    exportTable (type) {
      exportThird({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        // shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        payCode: this.payCode === '-1' ? '' : this.payCode,
        subMerchantId: this.payee === '-1' ? '' : this.payee,
        dateType: type
      }).then(res => {
        if (res.status === 200) {
          if (this.selectDateType === 'daterange') {
            blobToXls(res.data, `第三方支付统计表(${this.startDate.substring(0, 10)}-${dayjs(this.endDate).subtract(1, 'day').format('YYYY-MM-DD 00:00:00').substring(0, 10)})`)
          } else if (this.selectDateType === 'month') {
            blobToXls(res.data, `第三方支付统计表(${this.startDate.substring(0, 7)})`)
          } else {
            blobToXls(res.data, `第三方支付统计表(${this.startDate.substring(0, 10)})`)
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 筛选按钮
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    }
  }
}
</script>

<style>
</style>
